import React, { useEffect, useRef, useState } from 'react'
import styles from './index.module.scss'
import { Button, message, Tag } from 'antd'
import ExamDetail from '@/common_components/exam_detail'
import { useNavigate, useParams } from 'react-router-dom'
import { useAppDispatch, useAppSelector } from '@/store'
import { get_student_exam_topic_list_async, select_current_exam_topic_data, select_exam_topic_list, set_current_exam_topic_id, set_current_subject_two } from '@/store/slice/subject'
import { ExamTopicListDateType, postStudentExam } from '@/util/request'
import classNames from 'classnames'

// 考试界面
export default function Exam () {
  const params = useParams()
  const dispatch = useAppDispatch()
  const navigate = useNavigate()
  const [isVisible, setIsVisible] = useState(true);
  const numter = useRef(0)

  // 考题列表
  const exam_topic_list = useAppSelector(select_exam_topic_list)
  // 现在选中的题目
  const current_topic = useAppSelector(select_current_exam_topic_data)
  // 获取路由跳转时该二级课程的id
  const subject_two_id = params.subject_two_id as string
  // 根据每个题目是否作答来判断是否可以提交
  const is_submit = exam_topic_list.every((item: ExamTopicListDateType) => {
    return item.answer
  })
// 全屏控制
    const toggleFullscreen = async () => {
      try {
        if (!document.fullscreenElement) {
          await document.documentElement.requestFullscreen();
        } else {
          await document.exitFullscreen();
        }
      } catch (err) {
        console.error('全屏操作失败:', err);
      }
    };

  useEffect(() => {
    toggleFullscreen();
     // 监听全屏变化
      const fullscreenHandler = () => {
        if (!document.fullscreenElement) {
          navigate('/exam_select') // 退出全屏时自动返回
        }
      };
      
    document.addEventListener('fullscreenchange', fullscreenHandler);

    const handleVisibilityChange = () => {
      console.log(document.visibilityState === 'visible',document.visibilityState);
    
      if (document.visibilityState === 'visible') {
        message.error('切出屏幕3次将自动退出考试')
        setIsVisible(true);
        // 页面可见时，重新开始计时
      }else{
        if(isVisible){
          numter.current++
          if(numter.current >= 3){
            navigate('/exam_select')
          }
        }
        setIsVisible(false);
      }
    };

    // 监听 visibilitychange 事件
    document.addEventListener('visibilitychange', handleVisibilityChange);
    // 刷新页面后防止id消失
    dispatch(set_current_subject_two(subject_two_id))
    // 获取考题列表
    dispatch(get_student_exam_topic_list_async(subject_two_id))
    return () => {
      toggleFullscreen();
      document.removeEventListener('fullscreenchange', fullscreenHandler);
      document.removeEventListener('visibilitychange', handleVisibilityChange);
    }
  }, [])

  // 点击题目
  function clickTopic (item: ExamTopicListDateType) {
    // 设置当前选中的题目
    dispatch(set_current_exam_topic_id(item._id))
  }

  // 点击交卷
  async function submitExam () {
    const res = await postStudentExam({
      topic_list: exam_topic_list,
      two_id: subject_two_id
    })

    if (res.status === 201) {
      message.success('交卷成功')
      navigate('/exam_history')
    }
  }

  return (
    <div className={styles.wrap}>
      <div className={styles.list}>
        <div className={styles.title}>考题列表</div>
        <ul>
          {exam_topic_list.map((item, index) => {
            return (
              <li className={classNames({ active: item._id === current_topic?._id ,listSpan: styles.listSpan })} key={item._id} onClick={() => clickTopic(item)}>
                <p className={styles.listP}>
                  <div className={styles.listSpan}>{`${index + 1}. ${item.title}`}</div> {
                  item.answer ? <Tag color="green">已答题</Tag> : ''
                  }
                </p>
              </li>
            )
          })}
        </ul>
      </div>
      <div className={styles.detail}>
        <ExamDetail type="exam" topic={current_topic!}></ExamDetail>
        <Button disabled={!is_submit} type="primary" className={styles.submit} onClick={() => submitExam()}>
          点击交卷
        </Button>
      </div>
    </div>
  )
}
